package com.inmerweb.app.dao;


import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.util.Assert;

import com.inmerweb.app.commons.dao.GenericJpaDao;
import com.inmerweb.app.domain.UserEntity;

/**
 * DAO implementacion para las operaciones de usuario
 * 
 * @author Daniel Pascual Sanchez
 *
 */
public class UserJpaDao extends GenericJpaDao<UserEntity, Long> implements
		UserDao {

	public UserJpaDao() {
		super(UserEntity.class);
	}

	public boolean checkAvailable(String userName) {
		// Comprobar que la consulta no contiene nombre de usuario nulo
		Assert.notNull(userName);
		// Lanzar la query con el parametro userName
		Query query = getEntityManager().createQuery(
				"select count(*) from " + getPersistentClass().getSimpleName()
						+ " u where u.userName =:userName").setParameter(
				"userName", userName);
		// Analizar el numero de resultados y devolver si no hay ninguno
		Long count = (Long) query.getSingleResult();

		return count < 1;

	}

	public UserEntity loadUserByUserName(String userName) {

		Assert.notNull(userName);
		UserEntity user = null;
		Query query = getEntityManager().createQuery(
				"select u from " + getPersistentClass().getSimpleName()
						+ " u where u.userName = :userName").setParameter(
				"userName", userName);

		try {
			user = (UserEntity) query.getSingleResult();
			getEntityManager().close();

		} catch (NoResultException e) {
			// no lanzar excepcion
			// TODO log4j
		}
		return user;
	}

}
